package com.swak.frame.job;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.common.collect.Lists;
import com.swak.frame.dto.ListPager;
import com.swak.frame.util.DateTimeUtils;
import com.swak.frame.util.EmptyObject;
import com.swak.frame.util.ObjectUtil;

public abstract class RefreshListStateCache<K, V> extends RefreshableStateCache<K, V> {

    /** list缓存 缓存对应个的返回顺序，e.g 内存分页等 **/
    private Cache<Integer, List<V>> allSegment;


    @Override
    public synchronized void clear() {
        super.clear();
        allSegment.invalidateAll();
        logger.warn("Clear allSegment successfully >>>>>>>>>>>>>>>>>>>>> at {}",
            DateTimeUtils.sysTimeStr());
    }

    @Override
    public List<V> loadDataFrom() {
        List<V> result = super.loadDataFrom();
        if (!isValid(result)) {
            logger.error("Data validation failed,cacheName:{},result:{}", cacheName(),
                JSON.toJSONString(result));
        }
        // 不为空直接替换缓存中的老数据
        if (CollectionUtils.isNotEmpty(result)) {
            allSegment.put(0, result);
        }
        return result;
    }

    public List<V> getAll() {
        List<V> list = allSegment.getIfPresent(0);
        if (CollectionUtils.isEmpty(list)) {
            super.refresh();
            list = allSegment.getIfPresent(0);
        }
        if (CollectionUtils.isNotEmpty(list)) {
            List<V> newDatalist = Lists.newArrayListWithCapacity(list.size());
            list.forEach(data -> {
                newDatalist.add(ObjectUtil.cloneIfPossible(data));
            });
            return newDatalist;
        }

        return EmptyObject.emptyList();
    }

    /**
     * 分页获取缓存数据
     * 
     * @param pageIndex
     * @param pageSize
     * @return DataListPager<V>
     */
    public ListPager<V> getByPager(Integer pageIndex, Integer pageSize) {
        List<V> all = getAll();
        if (all == null) {
            all = EmptyObject.emptyList();
        }
        return new ListPager<V>(all.size(), pageIndex, pageSize).setItem(all);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        allSegment = Caffeine.newBuilder().maximumSize(500).build();
    }

    public static void main(String[] args) {
        Cache<Integer, String> allSegment = Caffeine.newBuilder().maximumSize(500).build();
        allSegment.put(0, "123");
        System.out.println(allSegment.getIfPresent(0));
        allSegment.put(0, "345");
        System.out.println(allSegment.getIfPresent(0));
    }
}
